/*
 * Copyright 2020 DuJiang.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rc.saas.tenant.crypto.advice;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.rc.saas.tenant.crypto.annotation.RequestBodyDecrypt;
import com.rc.saas.tenant.crypto.boot.RestCryptoProperties;
import com.rc.saas.tenant.crypto.util.CryptoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * DecryptRequestBodyAdvice
 * 
 * @author DuJiang
 */
@ControllerAdvice
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	private RestCryptoProperties cryptoProperties;

	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return methodParameter.getMethod().isAnnotationPresent(RequestBodyDecrypt.class);
	}

	@Override
	public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		try {
			DecryptHttpInputMessage decryptHttpInputMessage = new DecryptHttpInputMessage(inputMessage, String.valueOf(cryptoProperties.getAesKey()), String.valueOf(cryptoProperties.getAesIv()), cryptoProperties.getCharset());
			return decryptHttpInputMessage;
		} catch (Exception e) {
			log.error("RequestBody decryption failed", e);
		}
		return inputMessage;
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return body;
	}

	public class DecryptHttpInputMessage implements HttpInputMessage {

		private HttpHeaders headers;
		private InputStream body;

		public DecryptHttpInputMessage(HttpInputMessage inputMessage, String aesKey, String aesIv, String charset) throws IOException {
			this.headers = inputMessage.getHeaders();

			try {
				String bodyText = new BufferedReader(new InputStreamReader(inputMessage.getBody())).lines().collect(Collectors.joining(System.lineSeparator()));
				JSONObject jsonObject = JSON.parseObject(bodyText);
				Set<Entry<String, Object>> entrySet = jsonObject.entrySet();
				for (Entry<String, Object> entry : entrySet) {
					jsonObject.put(entry.getKey(), CryptoUtils.aesDecrypt(entry.getValue().toString(), aesKey, aesIv, charset));
				}
				this.body = new ByteArrayInputStream(jsonObject.toJSONString().getBytes());
			} catch (Exception e) {
				log.error(e.getMessage());
				this.body = inputMessage.getBody();
			}
		}

		@Override
		public InputStream getBody() {
			return body;
		}

		@Override
		public HttpHeaders getHeaders() {
			return headers;
		}
	}

}